package com.xiaotu.implCallable;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;

/**
 * @Author xiaotu
 * @Description //TODO
 * @Date 2022/3/25 10:43
 * @ClassName TestCallable01
 * @Version 1.0
 * 创建线程方式三:实现Callable接口
 **/
public class TestCallable01 implements Callable<Boolean> {
    private String url;
    private String name;

    public TestCallable01(String url, String name) {
        this.name = name;
        this.url = url;
    }

    @Override
    public Boolean call() throws Exception {
        com.xiaotu.implCallable.DownLoader downLoader = new com.xiaotu.implCallable.DownLoader();
        downLoader.downloads(url, name);
        System.out.println("下载了文件名为" + name);
        return true;
    }

    public static void main(String[] args) {
        TestCallable01 t1 = new TestCallable01("https://img2.baidu.com/it/u=2090606195,1473750087&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500", "美女.jpg");
        TestCallable01 t2 = new TestCallable01("https://img2.baidu.com/it/u=1790834130,1952230725&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500", "叮当猫.jpg");
        TestCallable01 t3 = new TestCallable01("https://img2.baidu.com/it/u=1777042033,1463932871&fm=253&fmt=auto&app=138&f=JPEG?w=400&h=400", "邮政.jpg");
        //创建执行服务
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        //提交执行
        Future<Boolean> R1 = executorService.submit(t1);
        Future<Boolean> R2 = executorService.submit(t2);
        Future<Boolean> R3 = executorService.submit(t3);
        try {
            //获取结果
            Boolean aBoolean = R1.get();
            Boolean bBoolean = R2.get();
            Boolean cBoolean = R3.get();
            //关闭服务
            executorService.shutdownNow();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }
}

class DownLoader {
    //下载方法
    public void downloads(String url, String name) {
        try {
            FileUtils.copyURLToFile(new URL(url), new File(name));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
